



#include <iostream>
#include <fstream>

#include <stdio.h>
#include "VinDefines.h"
#include "VinH264Decoder.h"
#include "VinH264PostDecoder.h"

const int MaxBufferLength = 5000;

using namespace std;



void printAndExit (const char* errorMessage);

void printResult(UInt32 result);

void main ()
{
    UInt32 result = kDecoderNoError;

    char* inFileName  = "encodedFile.264";
    char* outFileName = "decodedFile.yuv";

    ifstream *inFile = new ifstream(inFileName, ios::in | ios::binary);
    if ( inFile == NULL ) {
        printAndExit("File Opening Failed!");
    }

    UInt8* encodedFrame = new UInt8[MaxBufferLength];
    if ( encodedFrame == NULL ) {
        printAndExit("Buffer allocation failed");
    }

    PostDecoder* postDecoder = new PostDecoder(outFileName);
    if ( postDecoder == NULL ) {
        printAndExit("Decoded Frame sinc module failed\n");
    }

    VinH264Decoder* decoder = CreateDecoder();
    if ( decoder == NULL ) {
        printAndExit("Decoder instance creation failed\n");
    }

    result = decoder->InitVinH264Decoder(MaxBufferLength);
    if ( result != kDecoderNoError ) {
        printAndExit("Decoder initilization failed\n");
    }

    UInt32 bytesRead = 0;
    do {
        inFile->read((char*)encodedFrame, MaxBufferLength);
        bytesRead = inFile->gcount();

        if (bytesRead >= 0) {
            result = decoder->Decode(encodedFrame);
        }
    } while ( result == kDecoderNoError );

    if ( decoder != NULL ) {
        delete decoder;
        decoder = NULL;
    }

    if ( postDecoder != NULL ) {
        delete postDecoder;
        postDecoder = NULL;
    }

    if ( encodedFrame != NULL ) {
        delete [] encodedFrame;
        encodedFrame = NULL;
    }

    if ( inFile->is_open() ) {
        inFile->close();
        delete inFile;
        inFile = NULL;
    }
}




void printAndExit (const char* errorMessage)
{
    cout<<errorMessage<<endl;
    char ch;
    cin>>ch;
    exit(0);
}


void printResult (UInt32 result)
{
    cout<<result<<endl;
}